import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('@/pages/home/home')
    },
    {
      path: '/class',
      name: 'class',
      component: () => import('@/pages/class/class'),
      redirect: '/one',
      children: [
        {
          path: '/one',
          name: 'one',
          component: () => import('@/pages/class/classone')
        },
        {
          path: '/two',
          name: 'two',
          component: () => import('@/pages/class/classtwo')
        },
        {
          path: '/three',
          name: 'three',
          component: () => import('@/pages/class/classthree')
        },
        {
          path: '/four',
          name: 'four',
          component: () => import('@/pages/class/classfour')
        }
      ]
    },
    {
      path: '/cart',
      name: 'cart',
      component: () => import('@/pages/cart/cart')
    },
    {
      path: '/center',
      name: 'center',
      meta: { requiresAuth: true }, // 添加表示需要验证
      component: () => import('@/pages/center/center')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/pages/login/login')
    },
    {
      path: '/registered',
      name: 'registered',
      component: () => import('@/pages/registered/registered')
    },

    // 结算页面
    {
      path: '/buy',
      name: 'buy',
      component: () => import('@/pages/buy/buy'),
      meta: {
        keepAlive: true     //需要缓存
      }
    },
    // 收货地址页面 
    {
      path: '/goaddress',
      name: 'goaddress',
      component: () => import('@/pages/goaddress/goaddress'),
      meta: {
        keepAlive: true    //需要缓存
      }
    }
  ]

})

// 挂载前置导航守卫
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    if (!sessionStorage.token) {
      next({
        name: 'login'
      })
    } else {
      next();
    }
  } else {
    next()
  }
})

export default router
